<template>
  <div class="btndom">
    <el-upload
      ref="uploadRef"
      class="btn"
      action=""
      accept="zip"
      :multiple="false"
      :on-change="openGeoJSON"
      :file-list="fileList"
      :on-preview="flyto"
      :on-remove="removelayer"
      :auto-upload="false"
      :limit="1"
    >
      <el-button size="small" type="primary">点击上传</el-button>
      <!-- <div slot="tip" class="el-upload__tip">
        只能上传jpg/png文件，且不超过500kb
      </div> -->
    </el-upload>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";
// import { useMapStore } from "@/stores/counter";
// const mapStore = useMapStore();
import * as mars3d from "mars3d";
import * as shpUtil from "shp-geojson";
import simplifygeojson from "simplify-geojson";
let map, gl;
let filename = "";

const emit = defineEmits(["shploaded", "flytoshp", "removelayer"]);
const props = defineProps({
  map: {
    type: Object,
    default: () => {},
  },
});
onMounted(() => {
  map = props.map;
  // map = mapStore.map;

  gl = new mars3d.layer.GraphicLayer({
    id: 88888,
    name: "临时绘制图层",
    // popup: "all",
  });
  // gl = map.getLayerById(110);
  // if (!gl.isAdded) {
  //   map.addLayer(gl);
  // }

  gl.show = true;

  // gl.on(mars3d.EventType.click, (e) => {
  //   console.log(e.graphic.attr);
  // });

  map.addLayer(gl);
});

const fileList = ref();
const uploadRef = ref();

const openGeoJSON = (info) => {
  if (info.status !== "success") {
    info.status = "success";
    openshp(info.raw);
  }
};
const flyto = () => {
  const rec = gl.getRectangle(true);
  // gl.flyTo();
  emit("flytoshp", rec);
  // map.flyToExtent(rec, {
  //   duration: 0.5,
  // });
};
const removelayer = (file) => {
  // gl.clear();
  // 需要按文件名进行移除
  const graphics = gl.getGraphicsByAttr(file.name.split(".")[0], "filename");
  graphics.map((item) => {
    gl.removeGraphic(item);
  });

  emit("removelayer", file);
};

const clearAll = () => {
  gl.clear();
};

const clearfilelist = () => {
  uploadRef.value.clearFiles();
};

// 打开解析shp文件
const openshp = (file: any) => {
  const fileName = file.name;
  const fileType = fileName
    ?.substring(fileName.lastIndexOf(".") + 1, fileName.length)
    .toLowerCase();
  if (gl.isAdded === false) {
    // map.addLayer(gl)
  }
  if (fileType === "zip" || fileType === "rar") {
    const reader = new FileReader();
    reader.readAsArrayBuffer(file);
    reader.onloadend = function (e) {
      const json = this.result;
      shpUtil.toGeoJSON(json).then((geojson) => {
        const _geojson = simplifygeojson(geojson, 0.0001, false);

        filename = geojson.fileName;
        if (geojson.features[0].geometry.type === ("Point" || "MultiPoint")) {
          gl.loadGeoJSON(_geojson, {
            type: "pointP",
            // clear: true,
            style: {
              color: "#ff0000",
              pixelSize: 10,
              clampToGround: true,
              outlineColor: "#ffffff",
              outlineWidth: 2,
            },
            onEachFeature: function (feature) {
              feature.attr = { ...feature.attr, filename: filename };
              return feature;
            },
          });
          // console.log(gl);
        } else if (
          geojson.features[0].geometry.type ===
          ("LineString" || "MultiLineString")
        ) {
          gl.loadGeoJSON(_geojson, {
            type: "polylineP",
            // clear: true,
            style: {
              width: 2,
              clampToGround: true,
              color: "#ff0000",
            },
            onEachFeature: function (feature) {
              feature.attr = { ...feature.attr, filename: filename };
              return feature;
            },
          });
          // console.log(gl);
        } else if (
          geojson.features[0].geometry.type === ("Polygon" || "MultiPolygon")
        ) {
          gl.loadGeoJSON(_geojson, {
            type: "polygonP",
            // clear: true,
            // flyto: true,
            style: {
              color: "#ff4454",
              opacity: 0.3,
              outline: true,
              clampToGround: true,
              outlineWidth: 3,
              outlineColor: "#ffffff",
            },
            onEachFeature: function (feature) {
              feature.attr = { ...feature.attr, filename: filename };
              return feature;
            },
          });
          // console.log(gl);
        }

        emit("shploaded", {
          geojson: _geojson,
          filename: fileName,
        });
      });
    };
  }
};
defineExpose({
  clearAll,
  clearfilelist,
});
</script>
<style lang="less">
.btndom {
  width: 100%;
}
</style>
